package com.sunwayworld.baseline.qywx.login.utils;

import com.mchange.v1.io.InputStreamUtils;
import com.sunwayworld.framework.cache.redis.RedisHelper;
import com.sunwayworld.framework.utils.ObjectUtils;
import org.apache.commons.io.FileUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.boot.system.ApplicationHome;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

public class RestUtil {
    private static final Logger log = LogManager.getLogger(RestUtil.class);


    public static String getJsonFromFile(String prefix) {
        String json = null;
        try {
            if (ObjectUtils.isEmpty(RedisHelper.get("QYWX", prefix.toUpperCase()))) {
                // 优先从项目所在目录读取配置文件
                ApplicationHome applicationHome = new ApplicationHome();
                File jsonFile = new File(applicationHome.getDir(), "/"+prefix+".json");
                if (jsonFile.exists()) {
                    json = FileUtils.readFileToString(jsonFile);
                } else {
                    InputStream in = RestUtil.class.getClassLoader().getResourceAsStream(prefix+".json");
                    assert in != null;
                    json = InputStreamUtils.getContentsAsString(in);
                }
                if (json != null) {
                    RedisHelper.getRedisTemplate().opsForValue().setIfAbsent(getRedisKey("QYWX", prefix.toUpperCase()), json);
                }
            } else {
                json = RedisHelper.get("QYWX", prefix.toUpperCase());
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return json;
    }

    private static String getRedisKey(String cacheName, String cacheKey) {
        return cacheName + "::" + cacheKey;
    }
}
